import { ref } from 'vue'
// import { useRouter } from 'vue-router'
import router from '../router'
import { defineStore } from 'pinia'
import { login, logout, getUserInfo } from '@/api/test'
import type { MenuItem } from '@/router/dynamic'
import DefaultLayout from '@/layouts/Default.vue'

interface UserInfo {
    username: string
    nickname: string
    avatar: string
    email: string
    phone: string
    menus: any[]
}

export const useUserStore = defineStore('user', () => {
    const menuIsCollapse = ref(false)
    const hasDynamicRoutes = ref(false)
    const menus = ref<MenuItem[] | null>(localStorage.getItem('menus') ? JSON.parse(localStorage.getItem('menus') as string) : null)
    const token = ref<string | null>(localStorage.getItem('token'))
    const userInfo = ref<UserInfo | null>(localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo') as string) : null)

    /**
     * 登录
     */
    const toLogin = async (loginForm: { username: string; password: string }) => {
        const res: any = await login(loginForm)
        token.value = res.data.token
        userInfo.value = res.data.adminInfo
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('userInfo', JSON.stringify(res.data.adminInfo))
    }
    /**
     * 获取用户信息
     */
    const fetchUserInfo = async () => {
        const res: any = await getUserInfo()
        userInfo.value = res.data
        if (res.data.menus) {
            menus.value = res.data.menus
            localStorage.setItem('menus', JSON.stringify(res.data.menus))
        }
        localStorage.setItem('userInfo', JSON.stringify(res.data))
    }
    /**
     * 退出登录
     */
    const toLogout = async () => {
        await logout()
        localStorage.clear()
        // localStorage.removeItem('token')
        // localStorage.removeItem('userInfo')
        token.value = null
        userInfo.value = null
        menus.value = []
    }

    return {
        menuIsCollapse,
        token,
        userInfo,
        toLogin,
        toLogout,
        fetchUserInfo,
        menus,
        hasDynamicRoutes
    }
})
